package com.ruoyi.littleRedBook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.littleRedBook.domain.pojo.Notification;
import com.ruoyi.littleRedBook.domain.pojo.Product;
import com.ruoyi.littleRedBook.mapper.NotificationMapper;
import com.ruoyi.littleRedBook.mapper.ProductMapper;
import com.ruoyi.littleRedBook.service.AdminProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AdminProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements AdminProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private NotificationMapper notificationMapper;

    @Override
    public AjaxResult getPendingProducts(Integer pageNum, Integer pageSize) {
        Page<Product> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0) // 0-待审核
                    .orderByAsc("created_at"); // 按提交时间正序（先提交先审核）
        Page<Product> productPage = productMapper.selectPage(page, queryWrapper);
        return AjaxResult.success(productPage.getRecords());
    }

    @Override
    public AjaxResult approveProduct(Long id) {
        // 校验商品存在且状态为待审核
        Product product = productMapper.selectById(id);
        if (product == null) {
            return AjaxResult.error("商品不存在");
        }
        if (product.getStatus() != 0) {
            return AjaxResult.error("仅待审核商品可操作");
        }

        // 更新商品状态为审核通过（1）
        product.setStatus(1);
        product.setUpdatedAt(LocalDateTime.now());
        int rows = productMapper.updateById(product);
        if (rows <= 0) {
            return AjaxResult.error("审核操作失败");
        }

        // 发送审核通过通知给卖家
        sendProductNotification(product.getSellerId(), 3, product.getId(),
                              "商品审核通过", "您的商品《" + product.getTitle() + "》已审核通过，已上架销售");

        return AjaxResult.success("审核通过成功");
    }

    @Override
    public AjaxResult rejectProduct(Long id, String rejectReason) {
        if (rejectReason == null || rejectReason.trim().isEmpty()) {
            return AjaxResult.error("驳回原因不能为空");
        }

        // 校验商品存在且状态为待审核
        Product product = productMapper.selectById(id);
        if (product == null) {
            return AjaxResult.error("商品不存在");
        }
        if (product.getStatus() != 0) {
            return AjaxResult.error("仅待审核商品可操作");
        }

        // 更新商品状态为审核驳回（2）+ 记录驳回原因
        product.setStatus(2);
        product.setRejectReason(rejectReason);
        product.setUpdatedAt(LocalDateTime.now());
        int rows = productMapper.updateById(product);
        if (rows <= 0) {
            return AjaxResult.error("审核操作失败");
        }

        // 发送审核驳回通知给卖家
        sendProductNotification(product.getSellerId(), 3, product.getId(),
                              "商品审核驳回", "您的商品《" + product.getTitle() + "》未通过审核，原因：" + rejectReason);

        return AjaxResult.success("审核驳回成功");
    }

    @Override
    public AjaxResult getApprovedProducts(Integer status, Integer pageNum, Integer pageSize) {
        // 校验状态合法性（1-通过 2-驳回 3-下架 4-售出）
        if (status != 1 && status != 2 && status != 3 && status != 4) {
            return AjaxResult.error("不支持的商品状态");
        }

        Page<Product> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", status)
                    .orderByDesc("updated_at"); // 按更新时间倒序
        Page<Product> productPage = productMapper.selectPage(page, queryWrapper);
        return AjaxResult.success(productPage.getRecords());
    }

    // 发送商品相关通知
    private void sendProductNotification(Long userId, Integer type, Long relatedId, String title, String content) {
        Notification notification = new Notification();
        notification.setUserId(userId);
        notification.setType(type);
        notification.setRelatedId(relatedId);
        notification.setTitle(title);
        notification.setContent(content);
        notification.setIsRead(0);
        notification.setCreatedAt(LocalDateTime.now());
        notificationMapper.insert(notification);
    }
}
